package com.daxt.common.exception;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;

import java.sql.BatchUpdateException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice("com.daxt.controller")
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
//	@ResponseBody
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public Result<String> exceptionHandler(MethodArgumentNotValidException e)
//    {
//        return ResultUtil.data(ResultCode.PARAM_ERROR.getCode(), e.getBindingResult().getFieldError().getDefaultMessage(), null);
//    }

//    // modified by dm @date:2021-05-21  解决日志不显示异常的问题
//    // 需要controller throw exception
//    // 而不是try catch 自己处理
//    @ExceptionHandler(Exception.class)
//    public String handleDuplicateKeyException(Exception e) {
//        logger.error(e.getMessage(), e);
//        return e.getMessage();
//    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result notFount(RuntimeException e)
    {
        if(!ObjectUtil.isEmpty(e.getCause()) && e.getCause() instanceof BatchUpdateException){
            logger.error("数据库异常:", e);
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "数据库异常", e.getCause().getMessage());
        }
        if(!ObjectUtil.isEmpty(e.getCause()) && e.getCause() instanceof JSONException){
            logger.error("JSON异常:", e);
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "JSON异常", e.getCause().getMessage());
        }
        if(!ObjectUtil.isEmpty(e.getCause()) && e.getCause() instanceof SQLIntegrityConstraintViolationException){
            logger.error("SQL完整约束违反异常:", e);
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "SQL完整约束违反异常", e.getCause().getMessage());
        }
        logger.error("运行时异常:", e);
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "运行异常，请联系管理员", e.getMessage());
//        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "运行时异常:" + e.getMessage(), null);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e)
    {
        logger.error(e.getMessage(), e);
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "服务器错误，请联系管理员", null);
    }

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException e)
    {
        logger.error(e.getMessage(), e);
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), e.getMsg().toString(), null);
    }


	
	/*@ExceptionHandler(value=MethodArgumentNotValidException.class)
	 @ResponseBody
	 public Result exception(HttpServletRequest request,MethodArgumentNotValidException e){
		 String msg=e.getMessage();
		 if(msg.startsWith("Validation failed for argument")&&msg.contains("default message")) {
			 int indexOf = msg.lastIndexOf("default message");
			 if(indexOf!=-1) {
				 String str=msg.substring(msg.lastIndexOf("[")+1 ,msg.lastIndexOf("]")-1);
					 return ResultUtil.data(ResultCode.RESULT_CHECK.getCode(),str ,null); 
				 
			 }
		 }
	return ResultUtil.data("500",e.getMessage(),null);

	}*/
	
	/* @ExceptionHandler
	    @ResponseBody
	    @ResponseStatus(value=HttpStatus.BAD_REQUEST)
	    public Result handle(ValidationException exception) {
	        if(exception instanceof ConstraintViolationException){
	           String msg=exception.getMessage();
	   		 if(msg.startsWith("Validation failed for argument")&&msg.contains("default message")) {
	   			 int indexOf = msg.lastIndexOf("default message");
	   			 if(indexOf!=-1) {
	   				 String str=msg.substring(msg.lastIndexOf("[")+1 ,msg.lastIndexOf("]")-1);
	   					 return ResultUtil.data(ResultCode.RESULT_CHECK.getCode(),str ,null); 
	   				 
	   			 }
	   		 }
	        }
	        return null;
	    }*/

}
